package indi.kider.server.bill.service;

import com.alibaba.fastjson.JSON;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.util.HttpClientUtils;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.bill.exception.ProduceBillException;
import indi.kider.server.bill.mapper.RentInfoDayMapper;
import indi.kider.server.bill.model.BillPercentage;
import indi.kider.server.bill.model.CommRespModel;
import indi.kider.server.bill.model.MeterAnbsValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 表具设备请求访问的工具类
 *
 * @author wangjingjing
 * @create 2018-09-20 下午5:45
 **/
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Slf4j
@Service
public class MeterCentreUtil {

    @Autowired
    private RentInfoDayMapper rentInfoDayMapper;

    @Autowired
    private HousesMapper housesMapper;

    //
//    private static final String URL_Y = "http://meter.woniugm.com/meterdata/getMeterConsumptionByTenant";
//
//    private static final String URL_R = "http://meter.woniugm.com/meterdata/getTenantConsumptionByRefund";
//
//    private static final String URL_AR = "http://meter.woniugm.com/meterdata/getMeterPublicValueByTenant";
    private static final String URL_Y = "http://meter-xp.hzpiz.com/meterdata/getMeterConsumptionByTenant";

    private static final String URL_R = "http://meter-xp.hzpiz.com/meterdata/getTenantConsumptionByRefund";

    private static final String URL_AR = "http://meter-xp.hzpiz.commeterdata/getMeterPublicValueByTenant";

    /**
     * 请求服务器是用量信息。
     *
     * @param url
     * @param params
     * @return
     * @throws ProduceBillException
     */
    private MeterAnbsValue queryCrmFromServers(String url, Map<String, String> params) throws ProduceBillException {
        // 不用实时抄表的结算方式，全部使用冻结的结算方式。
        String str = null;
        log.info("请求【url= {},参数{}】", url, params);
        try {
            str = HttpClientUtils.postForm(url, params, null, 10000, 10000);
            log.info("请求的结果【{}】", str);
        } catch (Exception e) {
            log.info("失败【{}】", e.getStackTrace());
        }
        //JSON.toJSONString(str)
        CommRespModel crm = JSON.parseObject(str, CommRespModel.class);
        try {
            MeterAnbsValue meterAnbsValue = crm.getData();
            // 校验结果，无任何业务意义
            meterAnbsValue.getEleConsumeValue();
            return meterAnbsValue;
        } catch (Exception e) {
            throw new ProduceBillException("请求结果为空异常");
        }
    }

    /**
     * 当天的单个用户的用量。
     *
     * @param tenantId
     * @param date
     * @return
     * @throws ProduceBillException
     */
    public MeterAnbsValue queryCrmFromServers(String tenantId, String date) throws ProduceBillException {
        Map<String, String> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("date", date);
        return queryCrmFromServers(URL_AR, map);
    }


    /**
     * 远程获取用量
     *
     * @param tenantId
     * @param startDate
     * @param endDate
     * @param pr
     * @param wr
     * @param hasReading
     * @return
     */
    public MeterAnbsValue queryCrmFromServers(String tenantId,
                                              String startDate,
                                              String endDate,
                                              String pr,
                                              String wr,
                                              boolean hasReading) throws ProduceBillException {
        String              url = URL_Y;
        Map<String, String> map = new HashMap<String, String>();
        map.put("tenantId", tenantId);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        if (hasReading) {
            map.put("pr", pr);
            map.put("wr", wr);
            url = URL_R;
        }
        return queryCrmFromServers(url, map);
    }

    /**
     * 请求的表用量后计算每个租住人员的用量
     *
     * @param meterAnbsValue
     * @param rent
     * @return
     */
    public MeterAnbsValue addProportion(MeterAnbsValue meterAnbsValue, Rent rent) {
        Long   housesId = rent.getHousesId();
        Houses houses   = housesMapper.selectByPrimaryKey(housesId);
        log.info("查询id=【{}】房屋信息，信息是【{}】", housesId, houses);
        Long   tenantId = rent.getTenantId();
        String pmc      = houses.getPowerMeter();
        String wmc      = houses.getWaterMeter();
        String sd       = meterAnbsValue.getSdate();
        String ed       = meterAnbsValue.getEdate();

        BillPercentage pBillPercentage = rentInfoDayMapper.queryPercentageByTenantId(tenantId, sd, ed, null, pmc);
        log.info("电表比例【{}】", pBillPercentage);
        /* 安比例计算电用量*/
        Float ele = Float.valueOf(meterAnbsValue.getEleConsumeValue());
        if (pBillPercentage.getTenCount() > 0) {
            ele = ele * pBillPercentage.getTenCount() / pBillPercentage.getAllCount();
            //throw new ProduceBillException("电表统计比例没有，不需要计算账单");
        } else {
            log.info("电表统计比例没有");
            ele = 0f;
        }

        meterAnbsValue.setEleConsumeValue(ele.toString());

        BillPercentage wBillPercentage = rentInfoDayMapper.queryPercentageByTenantId(tenantId, sd, ed, wmc, null);
        log.info("水表比例【{}】", wBillPercentage);
        Float wsv = Float.valueOf(meterAnbsValue.getWaterConsumeValue());
        /* 安比例计算水用量*/
        if (wBillPercentage.getTenCount() > 0) {
            //throw new ProduceBillException("水表统计比例没有，不需要计算账单");
            wsv = wsv * wBillPercentage.getTenCount() / wBillPercentage.getAllCount();
        } else {
            log.info("水表统计比例没有");
            wsv = 0f;
        }
        meterAnbsValue.setWaterConsumeValue(wsv.toString());

        return meterAnbsValue;
    }

}
